﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static Cemit.NetFramework.PolyNetwork;
using Google.Protobuf;
using Cemit.PolyProto;
using Cemit.Awaiter;
using Cemit.NetFramework.Logger;

namespace Cemit.NetFramework
{
    /// <summary>进入一个帧同步的游戏房间</summary>
    [System.Obsolete("使用GameRoom类")]
    public class PolyGameRoom
    {
        public PolyPlayer[] Players { get; private set; }
        public OperationFrameBuffer FrameBuffer { get; private set; }
        public int ID { get; }
        public string PlayerName { get; }

        private readonly string ip;
        private readonly int port;


        private PolySocket gameServer;

        public PolyGameRoom(GameRoomInfo roomInfo, string playerName)
        {
            ip = roomInfo.Ip;
            port = roomInfo.Port;
            ID = roomInfo.RoomId;
            PlayerName = playerName;

            List<PolyPlayer> polyPlayers = new List<PolyPlayer>();

            foreach (var item in roomInfo.PlayerIds)
            {
                polyPlayers.Add(new PolyPlayer
                {
                    id = item
                });
            }

            Players = polyPlayers.ToArray();
        }

        [System.Obsolete("使用GameRoom(Data_GameRoomInfo)")]
        public PolyGameRoom(string ip, int port, int roomId, string playerName)
        {
            this.ip = ip;
            this.port = port;
            this.ID = roomId;
            this.PlayerName = playerName;
        }

        public async Task<bool> Join()
        {
            gameServer = new PolySocket()
                .SetLogger(Debug.Log, Debug.LogWarning, Debug.LogError) //设置Logger
                .RegisterToFireMessage() //添加分发消息的逐帧处理
                .RegisterToPingUpdate(); //添加处理ping相关的逐帧处理;

            var connectResult = await gameServer.Connect(ip, port);

            //连接服务器失败
            if (!connectResult.isSucceed)
            {
                Debug.LogWarning("加入房间失败：无法连接至服务器！");
                return false;
            }

            LoginResult loginResult = await gameServer.Login(PlayerName);

            if (loginResult != LoginResult.Successful)
            {
                Debug.LogWarning($"登录游戏服务器失败：{loginResult}！");
                return false;
            }

            FrameBuffer = new OperationFrameBuffer();
            
            //收到帧消息时加入帧缓冲中
            gameServer.AddMessageListener<F>(
                    frame => FrameBuffer.AddFrame((F)frame));

            return true;
        }

        public void SendToServer(IMessage message)
        {
            gameServer.Send(message);
        }

        public PolyGameRoom ChangeState(string state)
        {
            gameServer.Send(new Msg_Game_ChangeState { State = state });
            return this;
        }
    }
}
